<template>
  <div class="register-container">
    <div class="register-card">
      <h2 class="register-title">创建新账户</h2>

      <el-form
          ref="registerFormRef"
          :model="registerForm"
          :rules="registerRules"
          label-width="100px"
      >
        <!-- 账户类型选择 -->
        <el-form-item label="账户类型" prop="role">
          <div class="role-selection">
            <div
                :class="['role-option', { 'selected': registerForm.role === 'BUYER' }]"
                @click="registerForm.role = 'BUYER'"
            >
              <el-icon class="role-icon"><User /></el-icon>
              <h3>买家</h3>
              <p>浏览和购买商品</p>
            </div>

            <div
                :class="['role-option', { 'selected': registerForm.role === 'SELLER' }]"
                @click="registerForm.role = 'SELLER'"
            >
              <el-icon class="role-icon"><Shop /></el-icon>
              <h3>卖家</h3>
              <p>发布和管理商品</p>
            </div>
          </div>
        </el-form-item>

        <!-- 用户名 -->
        <el-form-item label="用户名" prop="username">
          <el-input
              v-model="registerForm.username"
              placeholder="设置您的用户名"
              prefix-icon="User"
          />
        </el-form-item>

        <!-- 密码  -->
        <el-form-item label="密码" prop="password">
          <el-input
              v-model="registerForm.password"
              :type="passwordVisible ? 'text' : 'password'"
              placeholder="设置登录密码"
              prefix-icon="Lock"
              show-password
              @input="checkPasswordStrength"
          />
          <!-- 密码强度指示器 -->
          <div class="password-strength">
            <div class="strength-bar" :style="{ width: passwordStrength + '%' }" :class="strengthClass"></div>
            <div class="strength-text">{{ passwordStrengthText }}</div>
          </div>
        </el-form-item>

        <!-- 确认密码 -->
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
              v-model="registerForm.confirmPassword"
              :type="passwordVisible ? 'text' : 'password'"
              placeholder="再次输入密码"
              prefix-icon="Lock"
          />
        </el-form-item>

        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input
              v-model="registerForm.email"
              placeholder="用于找回密码"
              prefix-icon="Message"
          />
        </el-form-item>

        <!-- 手机号 -->
        <el-form-item label="手机号" prop="phone">
          <el-input
              v-model="registerForm.phone"
              placeholder="用于找回密码"
              prefix-icon="Iphone"
              @input="registerForm.phone = registerForm.phone.replace(/\D/g, '')"
          />
        </el-form-item>

        <!-- 注册按钮 -->
        <el-form-item>
          <el-button
              type="primary"
              class="register-btn"
              @click="handleRegister"
              :loading="isRegistering"
          >
            立即注册
          </el-button>
        </el-form-item>
      </el-form>

      <div class="login-link">
        已有账号? <el-link type="primary" @click="goToLogin">立即登录</el-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { View, Hide, User, Shop } from '@element-plus/icons-vue';
import { useUserStore } from '@/stores/userStore';
import request from '@/utils/request';

const router = useRouter();
const userStore = useUserStore();

const registerForm = reactive({
  role: 'BUYER',
  username: '',
  password: '',
  confirmPassword: '',
  email: '',
  phone: ''
});

const registerFormRef = ref();
const isRegistering = ref(false);
const passwordVisible = ref(false);
const passwordStrength = ref(0);
const passwordStrengthText = ref('');

const strengthClass = computed(() => {
  if (passwordStrength.value < 40) return 'weak';
  if (passwordStrength.value < 70) return 'medium';
  return 'strong';
});

const registerRules = {
  role: [
    { required: true, message: '请选择账户类型', trigger: 'change' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在3-20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, message: '密码长度至少8位', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (!/(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/.test(value)) {
          callback(new Error('需包含大小写字母和数字'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    {
      validator: (_, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ]
};

const checkPasswordStrength = () => {
  const password = registerForm.password;
  if (!password) {
    passwordStrength.value = 0;
    passwordStrengthText.value = '';
    return;
  }

  let strength = 0;

  // 长度检查
  if (password.length >= 8) strength += 25;
  if (password.length >= 12) strength += 15;

  // 字符种类检查
  if (/[a-z]/.test(password)) strength += 15;
  if (/[A-Z]/.test(password)) strength += 15;
  if (/[0-9]/.test(password)) strength += 15;
  if (/[^A-Za-z0-9]/.test(password)) strength += 15;

  // 限制最大值
  passwordStrength.value = Math.min(strength, 100);

  // 设置强度文本
  if (passwordStrength.value < 40) {
    passwordStrengthText.value = '弱';
  } else if (passwordStrength.value < 70) {
    passwordStrengthText.value = '中';
  } else {
    passwordStrengthText.value = '强';
  }
};

const handleRegister = async () => {
  if (!registerFormRef.value) return;

  // 去除所有输入项前后空格，空字符串转为null
  for (const key in registerForm) {
    if (typeof registerForm[key] === 'string') {
      registerForm[key] = registerForm[key].trim();
      if (registerForm[key] === '') registerForm[key] = null;
    }
  }
  // role转为小写
  if (registerForm.role) {
    registerForm.role = registerForm.role.toLowerCase();
  }

  const valid = await registerFormRef.value.validate();
  if (!valid) return;

  isRegistering.value = true;

  try {
    // 调用后端注册接口（路径统一为/api/auth/register）
    const registerResponse = await request.post('/api/auth/register', {
      username: registerForm.username,
      password: registerForm.password,
      role: registerForm.role,
      email: registerForm.email,
      phone: registerForm.phone
    });

    // 注册成功后自动登录
    const loginResponse = await request.post('/api/auth/login', {
      username: registerForm.username,
      password: registerForm.password
    });

    // 保存用户信息和令牌
    userStore.login(
        loginResponse.user,
        loginResponse.token,
        loginResponse.refreshToken
    );

    // 显示成功消息
    const roleNames = {
      buyer: '买家',
      seller: '卖家',
      admin: '管理员'
    };
    const roleName = roleNames[registerForm.role] || '用户';

    ElMessage.success(`注册成功！欢迎${roleName}${registerForm.username}`);

    // 根据角色跳转
    const redirectMap = {
      admin: '/admin/dashboard',
      seller: '/seller/dashboard',
      buyer: '/'
    };

    router.push(redirectMap[registerForm.role] || '/');

  } catch (error) {
    let errorMsg = '注册失败，请重试';
    if (error.response?.data) {
      if (error.response.data.includes("用户名已存在")) {
        errorMsg = "该用户名已被注册";
      } else if (error.response.data.includes("邮箱已被注册")) {
        errorMsg = "该邮箱已被注册";
      } else {
        errorMsg = error.response.data;
      }
    }
    ElMessage.error(errorMsg);
  } finally {
    isRegistering.value = false;
  }
};

const goToLogin = () => {
  router.push('/login');
};
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 0 8px;
}

.register-card {
  width: 100%;
  max-width: 400px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  padding: 32px 24px;
  margin: 40px auto 0 auto;
}

.register-title {
  text-align: center;
  margin-bottom: 30px;
  color: #333;
  font-size: 24px;
}

.role-selection {
  display: flex;
  gap: 20px;
  margin-top: 10px;
}

.role-option {
  flex: 1;
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}

.role-option:hover {
  border-color: #409EFF;
  transform: translateY(-3px);
}

.role-option.selected {
  border-color: #409EFF;
  background-color: #f0f7ff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

.role-icon {
  font-size: 32px;
  color: #409EFF;
  margin-bottom: 10px;
}

.password-toggle {
  cursor: pointer;
  color: #606266;
  font-size: 18px;
  transition: color 0.3s;
}

.password-toggle:hover {
  color: #409EFF;
}

.password-strength {
  margin-top: 8px;
}

.strength-bar {
  height: 6px;
  border-radius: 3px;
  margin-bottom: 4px;
  transition: width 0.3s;
}

.strength-bar.weak {
  background-color: #ff4d4f;
}

.strength-bar.medium {
  background-color: #faad14;
}

.strength-bar.strong {
  background-color: #52c41a;
}

.strength-text {
  font-size: 12px;
  color: #606266;
}

.register-btn {
  width: 100%;
  height: 44px;
  font-size: 16px;
  background: linear-gradient(90deg, #4361ee, #3a0ca3);
  border: none;
  transition: all 0.3s;
}

.register-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(67, 97, 238, 0.3);
}

.login-link {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
  color: #606266;
}

@media (max-width: 768px) {
  .role-selection {
    flex-direction: column;
  }
}
</style>